import md5 from 'md5'
import Cookies from 'js-cookie'
import Must from './mustParameter'
/*
  对象排序拼接成字符串
*/
function sigSortObj (obj) {
  if (!obj) { return '' }
  const arr = []
  let sigString = ''
  for (const key in obj) { arr.push(key) }
  arr.sort()
  for (let i = arr.length - 1; i >= 0; i--) {
    const key = arr[i]
    const tail = i === 0 ? '' : '&'
    sigString = sigString + (key + '=' + obj[key]) + tail
  }
  return sigString
}

/*
  传入1个／2个 json对象，生成签名
*/
async function sigFunc (objArr, salt) {
// url 参数
  const param = await Must(objArr[0])
  const token = Cookies.get('token')
  if (token) { param.token = token }
  const str = sigSortObj(param)
  let sigString
  // get 请求
  if (objArr.length === 1) { sigString = `${str}&salt=${salt}` }
  // post 请求
  else {
    const str1 = sigSortObj(objArr[1])
    sigString = `${str1}&${str}&salt=${salt}`
  }

  const sig = md5(sigString)

  return { str, sig }
}

export default sigFunc
